import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { UserRepository } from '../repositories/user.repository.js'
import type { RegisterInput, LoginInput } from '@shared/types'

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production'
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d'

export class AuthService {
  private userRepository: UserRepository

  constructor() {
    this.userRepository = new UserRepository()
  }

  /**
   * 注册新用户
   */
  async register(input: RegisterInput) {
    // 检查邮箱是否已存在
    const existingUser = await this.userRepository.findByEmail(input.email)
    if (existingUser) {
      throw new Error('该邮箱已被注册')
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(input.password, 10)

    // 创建用户
    const user = await this.userRepository.create({
      email: input.email,
      password: hashedPassword,
      nickname: input.nickname,
      ...(input.age !== undefined && { age: input.age }),
      ...(input.sex !== undefined && { sex: input.sex })
    })

    // 生成 JWT token
    const token = this.generateToken(user.uid)

    // 返回用户信息（不包含密码）和 token
    return {
      token,
      user: {
        uid: user.uid,
        email: user.email || '', // 确保不为 null
        nickname: user.nickname,
        age: user.age,
        sex: user.sex,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt
      }
    }
  }

  /**
   * 用户登录
   */
  async login(input: LoginInput) {
    // 查找用户
    const user = await this.userRepository.findByEmail(input.email)
    if (!user) {
      throw new Error('邮箱或密码错误')
    }

    // 验证密码
    if (!user.password) {
      throw new Error('该用户没有设置密码')
    }
    const isPasswordValid = await bcrypt.compare(input.password, user.password)
    if (!isPasswordValid) {
      throw new Error('邮箱或密码错误')
    }

    // 生成 JWT token
    const token = this.generateToken(user.uid)

    // 返回用户信息（不包含密码）和 token
    return {
      token,
      user: {
        uid: user.uid,
        email: user.email || '', // 确保不为 null
        nickname: user.nickname,
        age: user.age,
        sex: user.sex,
        createdAt: user.createdAt,
        updatedAt: user.updatedAt
      }
    }
  }

  /**
   * 生成 JWT token
   */
  private generateToken(uid: string): string {
    return jwt.sign({ uid }, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN } as jwt.SignOptions)
  }

  /**
   * 验证 JWT token
   */
  verifyToken(token: string): { uid: string } | null {
    try {
      const decoded = jwt.verify(token, JWT_SECRET) as { uid: string }
      return decoded
    } catch (error) {
      return null
    }
  }
}
